package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.LonginBean;
import com.dinadi.yidi.bean.UserInfoBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.MyApplication;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.StringUtil;

/**
 * author: JiaYu.He
 * Date: 2017/3/20
 * Time: 13:42
 */

public class LoginActivity extends BaseActivity {
    private View view;
    private ImageView canle_login, clear_phone, is_show, btn_login;
    private EditText edit_phone, edit_pwd;
    private TextView btn_goto_forget, btn_goto_register;
    private boolean loginState;

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(LoginActivity.this).inflate(R.layout.activity_login, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        canle_login = (ImageView) view.findViewById(R.id.canle_login);
        clear_phone = (ImageView) view.findViewById(R.id.clear_phone);
        is_show = (ImageView) view.findViewById(R.id.is_show);
        btn_login = (ImageView) view.findViewById(R.id.btn_login);
        edit_phone = (EditText) view.findViewById(R.id.edit_phone);
        edit_pwd = (EditText) view.findViewById(R.id.edit_pwd);
        btn_goto_forget = (TextView) view.findViewById(R.id.btn_goto_forget);
        btn_goto_register = (TextView) view.findViewById(R.id.btn_goto_register);
        edit_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0)
                    clear_phone.setVisibility(View.GONE);
                else
                    clear_phone.setVisibility(View.VISIBLE);
            }
        });
        edit_pwd.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0)
                    is_show.setVisibility(View.GONE);
                else
                    is_show.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void initListener() {
        registerClickListener(is_show, clear_phone, canle_login, btn_goto_register, btn_goto_forget, btn_login);
        edit_pwd.setOnKeyListener(onKeyListener);
        edit_pwd.setOnEditorActionListener(editorActionListener);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.is_show:
                pwdShow();
                break;
            case R.id.clear_phone:
                edit_phone.setText("");
                break;
            case R.id.canle_login:
                LoginActivity.this.finish();
                break;
            case R.id.btn_goto_register:
                //注册
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                LoginActivity.this.finish();
                break;
            case R.id.btn_goto_forget:
                //忘记密码
                startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                LoginActivity.this.finish();
                break;
            case R.id.btn_login:
                //点击登陆
                login();
                break;
            default:
                break;
        }
    }

    private void login() {
        //显示网络请求框
        String phone = edit_phone.getText().toString();
        String pwd = edit_pwd.getText().toString();

        if (TextUtils.isEmpty(phone)) {
            toast(R.string.toast_phone);
            return;
        } else if (!StringUtil.isPhoneNumber(phone)) {
            toast(R.string.edit_need_phone_no);
            return;
        }


        boolean b = checkPass(pwd);

        if (!b) {
            return;
        } else {
            LonginBean bean = new LonginBean();
            bean.setUserName(phone);
            bean.setPwd(pwd);
            showLoadingDialog(getResources().getString(R.string.dialog_text_login));
            CommonInterface loginInterface = new CommonInterface(LoginActivity.this, httpListener);
            loginInterface.getInterface("10001", JSON.toJSONString(bean));

        }
    }

    // 检查密码
    public boolean checkPass(String password) {
        if (TextUtils.isEmpty(password)) {
            toast(R.string.edit_need_pwd);
            return false;
        }

        if (password.length() < 6) {
            toast(R.string.edit_need_pwd6);
            return false;
        }

        return true;
    }

    HttpListener httpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                //  startActivity(new Intent(LoginActivity.this, MainActivity.class));
                LoginActivity.this.finish();
                MyApplication.getApp().setUser(JsonUtil.parseJsonToBean(response, UserInfoBean.class));
                String userId = JsonUtil.getFieldValue(response, "userId");
                SharePreferencesHelper.getInstance(LoginActivity.this).putString("userId", userId);
                String token = JsonUtil.getFieldValue(response, "token");
                SharePreferencesHelper.getInstance(LoginActivity.this).putString("token", token);
                loginState = true;
                SharePreferencesHelper.getInstance(LoginActivity.this).putBoolean("loginState", loginState);
                /*项目中是否刷新的标记*/
                SharePreferencesHelper.getInstance(LoginActivity.this).putString("isRefresh", "yes");

            } else {
                closeLoadingDialog();
                loginState = false;
                SharePreferencesHelper.getInstance(LoginActivity.this).putBoolean("loginState", loginState);
                toast("手机号或密码错误");
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            loginState = false;
            SharePreferencesHelper.getInstance(LoginActivity.this).putBoolean("loginState", loginState);
            Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();

        }
    };

    public void pwdShow() {

        int type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
        if (edit_pwd.getInputType() == type) {
            edit_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            edit_pwd.setSelection(edit_pwd.getText().length()); // 把光标设置到当前文本末尾
            is_show.setImageResource(R.drawable.login_icon_password_display);
        } else {
            edit_pwd.setInputType(type);
            edit_pwd.setSelection(edit_pwd.getText().length());
            is_show.setImageResource(R.drawable.login_icon_password_hide);
        }

    }

    private final EditText.OnEditorActionListener editorActionListener =
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
                        login();
                    }
                    return true;
                }
            };

    /**
     * 点击回车就开始检索
     */
    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((KeyEvent.KEYCODE_ENTER == keyCode) &&
                    (KeyEvent.ACTION_DOWN == event.getAction())) {
                login();
                return true;
            }
            return false;
        }
    };
}
